package mud.controller;

import groovy.lang.Binding;
import mud.entity.Reply;
import mud.entity.MatchedLink;
import mud.entity.MatchedScript;
import mud.repository.MatchedLinkRepository;
import mud.repository.MatchedScriptRepository;
import mud.support.ScriptLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.net.MalformedURLException;
import java.net.URL;

@RestController
public class ScriptController {
    private final Logger log=LoggerFactory.getLogger(ScriptController.class);

    @Autowired
    private MatchedScriptRepository scriptRepository;

    @Autowired
    private MatchedLinkRepository linkRepository;

    @GetMapping(path = "/link")
    @ResponseBody
    public String analyze(
            @RequestParam(value = "url") String url) {
        MatchedLink link = linkRepository.findByLabel(getPrefix(url));
        if (link == null)
            return new Reply("暂时不支持的链接T_T").toString();
        else {
            MatchedScript script = scriptRepository.findByLabel(link.getDetail());
            if (script == null)
                return new Reply("暂时不支持的脚本T_T").toString();

            if (script.getDetail().isEmpty())
                return new Reply("脚本无效T_T").toString();

            Binding data = new Binding();
            data.setProperty("url", url);
            return new ScriptLoader().execute(script.getDetail(), data);
        }
    }

    public String getPrefix(String raw_url) {
        try {
            URL url = new URL(raw_url);
            String urlString=url.getProtocol() + "://" + url.getHost();
            log.info(urlString);
            return urlString;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
